//
//  CHHTTPSessionManager.swift
//  status
//
//  Created by 彳亍 on 2017/3/23.
//  Copyright © 2017年 彳亍. All rights reserved.
//

import UIKit
import AFNetworking

/// 网络请求类型
///
/// - GET: GET 请求
/// - POST: POST 请求
enum CHHttpType {
    case GET
    case POST
}

class CHHTTPSessionManager: AFHTTPSessionManager {
    
    /// 单例方法
    static let shared:CHHTTPSessionManager = {
        let instance = CHHTTPSessionManager()
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
    /// 用户账户
    lazy var account = CHAccount()
    
    /// 登录状态
    var logan:Bool {
        return account.access_token != nil
    }
    
    /// 网络请求
    ///
    /// - Parameters:
    ///   - type: 请求类型（GET／POST）
    ///   - URLString: 请求地址
    ///   - parameters: 请求参数
    ///   - completion: 完成回调
    func request(type:CHHttpType = CHHttpType.GET,URLString:String,parameters:Any?,completion:@escaping ((_ responseObect:Any?,_ isSuccess:Bool)->()) ) {
        
        /// 成功回调
        let success = { (dataTask:URLSessionDataTask, responseObject:Any?) in
            
            completion(responseObject,true)
        }
        
        /// 失败回调
        let failure = { (dataTask:URLSessionDataTask?,error:Error) in
            
            completion(error, false)
        }
        
        if type == CHHttpType.GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
    
    /// 网络请求
    ///
    /// - Parameters:
    ///   - type: 请求类型（GET／POST）
    ///   - URLString: 请求地址
    ///   - parameters: 请求参数
    ///   - completion: 完成回调
    func accessTokenRequest(type:CHHttpType = CHHttpType.GET,URLString:String,parameters:Any?,completion:@escaping ((_ responseObect:Any?,_ isSuccess:Bool)->())) {
        
        // 1. 获取AccessToken
        guard let accessToken = account.access_token else { return  }
        // 2. 准备参数
        var parameters = parameters as? [String:AnyObject]
        
        if parameters == nil {
            parameters = [String:AnyObject]()
        }
        
        parameters!["access_token"] = accessToken as AnyObject?
        
        // 发送网络请求
        request(type: type, URLString: URLString, parameters: parameters, completion: completion)
    }
}











